<template>
  <qx-table ref="RoleTable" :option="formOption" :remoteData="remoteData">
    <template v-slot:menuLeft="{ selected }">
      <q-btn v-auth="['authRole:save']" color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
      <q-btn v-auth="['authRole:update']" :disable="isDisable(selected)" icon="mdi-square-edit-outline" outline
             text-color="primary" @click="handleUpdate(selected[0])">
        {{ $t('Edit') }}
      </q-btn>
      <q-btn v-auth="['authRole:delete']" :disable="isDisable(selected)" icon="delete" outline text-color="primary"
             @click="handleDelete(selected[0])">
        {{ $t('Del') }}
      </q-btn>
    </template>
    <template v-slot:roleCode="{ row }">
      <q-link @click="handleCode(row)">{{ row.roleCode }}</q-link>
    </template>
  </qx-table>
  <qx-page v-model="pageVisible" :header="`${$t('SystemCore.RoleAssignMenu')}`" :menuBtn="false"
           classes="column no-wrap" fullHeight>
    <template v-slot:default>
      <ServiceRole v-model="pageVisible" :menuBtn="editAuth" :menusList="menusList" :rowInfo="rowInfo"></ServiceRole>
    </template>
  </qx-page>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="RoleCfg" v-model="formInfo" :option="formOption"></qx-form>
  </q-modal>
</template>

<script setup>
import { deleteAPI, postAPI, putAPI } from 'src/api'
import { i18n, toI18nName } from 'boot/i18n'
import { isAuth } from 'src/directives/v-auth'
import { yesOrNo } from 'src/enum'
import { createDialog, deepClone } from 'src/utils/utils'
import { userStores } from 'stores/user-stores'
import { computed, onMounted, ref } from 'vue'
import ServiceRole from './ServiceRole.vue'

const rowInfo = ref({})
const userStore = userStores()
const formInfo = ref({})
const RoleCfg = ref(null)
const searchForm = ref({})
const RoleTable = ref(null)
const pageVisible = ref(false)
const modalVisible = ref(false)

const editAuth = computed(() => {
  if (rowInfo.value.sysInner === '1') return import.meta.env.DEV || userStore.userInfo.sysInner === '1'
  return isAuth(['authRole:save', 'authRole:update'])
})
const isDisable = computed(() => selected => !selected || selected.length !== 1 || selected[0].sysInner === '1')
const formOption = computed(() => {
  return {
    labelWidth: 100, searchLabelWidth: 70, menuBtn: false, span: 22, selection: 'single',
    column: [{
      label: `${i18n.t('SystemCore.RoleCode')}`,
      field: 'roleCode',
      required: true,
      slot: true,
      minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.RoleNameENUS')}`,
      field: 'roleNameEnUs',
      hide: true,
      required: true,
      minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.RoleName')}`,
      field: 'roleNameZhCn',
      required: true,
      format: (_, row) => row[toI18nName('roleNameZhCn')],
      minWidth: 80
    }, {
      label: `${i18n.t('BuiltIn')}`,
      field: 'sysInner',
      search: false,
      display: false,
      options: yesOrNo.value,
      align: 'center', useTag: true,
      minWidth: 80
    }, {
      label: `${i18n.t('CreationTime')}`,
      field: 'createdTime',
      display: false,
      minWidth: 80
    }, {
      label: `${i18n.t('Remarks')}`,
      field: 'remark',
      type: 'textarea',
      search: false,
      minWidth: 120,
      maxlength: 200
    }]
  }
})

const handleCreate = () => {
  formInfo.value = {}
  modalVisible.value = true
}

const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}

const menusList = ref([])
const menusLoading = ref(false)

const handleCode = row => {
  menusLoading.value = true
  const params = { pageSize: '-1' }
  params.andDynamicQueryItems = [{ criterion: 'andEqualTo', property: 'roleId', value: row.id }]
  postAPI('/auth/api/authRole/listAuthRoleMenu', params, data => {
    menusList.value = data.rows.map(el => el.menuId)
    rowInfo.value = { ...row }
    menusLoading.value = false
    pageVisible.value = true
  }, () => {
    menusList.value = []
    menusLoading.value = false
  })
}

const formatSearchForm = () => {
  return { ...searchForm.value }
}

const remoteData = ref({ dicUrl: '/auth/api/authRole/listAuthRole' })
onMounted(() => startSearch())

const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/auth/api/authRole/${row.id}`, {}, () => startSearch())
  }, () => {})
}

const beforeClose = () => {
  if (RoleCfg.value) RoleCfg.value.onReset()
  modalVisible.value = false
}

const startSearch = (_, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
}

const submitForm = mDone => {
  RoleCfg.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    API('/auth/api/authRole', form, () => {
      startSearch()
      done()
      if (mDone) mDone()
    }, () => {
      done()
      if (mDone) mDone(false)
    })
  }, () => {
    if (mDone) mDone(false)
  })
}

</script>